// pages/jobs_detail/jobs_detail.js
const app = getApp(), core = require('../../utils/core'), chatIM = require('../../utils/websocket.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    group_id:1,
    markers: [],
    shops: [],
    comments:[],
    recomList: [],
    responsibility_limit:true,
    requirement_limit:true,
  },

  responsibility:function(e){
    this.setData({
      responsibility_limit: !this.data.responsibility_limit
    })
  },
  requirement: function (e) {
    this.setData({
      requirement_limit: !this.data.requirement_limit
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSystemInfo({
      success: function (res) {
        //model中包含着设备信息
        console.log(res.model)
        var model = res.model
        if (model.search('iPhone X') != -1) {
          app.globalData.isIpx = true;
        } else {
          app.globalData.isIpx = false;
        }
      }
    });
    let isPhone = app.globalData.isIpx;
    if (isPhone) {
      this.setData({
        ipx: true
      })
    }
    let group_id = app.getUserinfo() ? app.getUserinfo().group_id : 1;
    this.setData({jobId: options.id,group_id:group_id});
    this.getJobDetail();
    core.get({url:'xilujob.job/similar_jobs',data:{job_id:this.data.jobId},success:(ret)=>{this.setData({recomList:ret.data.data})}});
    // core.get({url:'xilujob.job/related_shops',data:{id:this.data.jobId},success:ret=>{this.setData({shops:ret.data.shops})}});
    core.get({url:'xilujob.interview_comment/lists',data:{job_id:this.data.jobId,pagesize:5},success:ret=>{this.setData({comments:ret.data.data,comment_count:ret.data.total})}});
    app.eventBus.on(app.Events.UserLogin, this.eventOnUserLogin, this);
  },
  getJobDetail() {
    core.get({
      url: '/xilujob.job/detail', data: {job_id:this.data.jobId},
      success: ret => {
        let job = ret.data.job;
        let images = job.enterpriseinfo.environment_images;
        images = images ? images.split(',') : [];
        //工作地址
        try {
          if(job.locations[0].lat) {
            let address = job.locations[0].province.name + job.locations[0].city.name + (job.locations[0].district?job.locations[0].district.name:'') + job.locations[0].address;
            this.data.markers.push({
              id: 1,
              latitude: job.locations[0].lat,
              longitude: job.locations[0].lng,
              width: 35,
              height: 35,
              callout: {
                content: address, //文本
                color: '#000000', //文本颜色
                borderRadius: 3, //边框圆角
                borderWidth: 1, //边框宽度
                borderColor: '#ffffff', //边框颜色
                bgColor: '#ffffff', //背景色
                padding: 5, //文本边缘留白
                display: "ALWAYS",
                textAlign: 'center' //文本对齐方式。有效值: left, right, center
              }
            });
          }
        }catch (e) {
          console.error(e);
        }

        this.setData({
          job: job, isFav: ret.data.is_fav, isApplying: ret.data.is_applying, isSignup: ret.data.is_signup,
          images: images, markers: this.data.markers, user: ret.data.user,
        })
      },fail: ret => {
        wx.navigateBack();
        wx.showToast({title: ret.msg,icon:'none'});
        return false;
      }
    });
  },
  bindMakeCall() {
    if(this.data.job.job_info.contact_phone.indexOf('*')!=-1) {
      let userinfo = app.getUserinfo(true);
      core.post({url:'xilujob.job/job_call',data:{job_id: this.data.jobId}, success: ret => {
        this.setData({'job.job_info.contact_phone':ret.data.phone});
        wx.makePhoneCall({phoneNumber: this.data.job.job_info.contact_phone});
      }});
    }else {
      wx.makePhoneCall({phoneNumber: this.data.job.job_info.contact_phone});
      core.post({url:'xilujob.job/job_call',data:{job_id: this.data.jobId}});
    }

  },
  
  // 收藏
  bindToggleFav() {
    if(!app.getUserinfo(true)) {
      return;
    }
    // if(app.getUserinfo().group_id!=1) {
    //   wx.showToast({title:'请切换到个人身份',icon:'none'});
    //   return;
    // }
    let page = this;
    page.setData({isFav: !this.data.isFav});
    core.post({url: '/xilujob.job/toggle_fav',loading:false,data:{job_id: this.data.jobId},success:(ret) => {
      page.setData({isFav: ret.data.is_fav});
      if(this.data.isFav) {
        app.eventBus.emit(app.Events.JobFavAdd, {job: this.data.job});
      }else {
        app.eventBus.emit(app.Events.JobFavRemove, {job: this.data.job});
      }
    },fail:ret=>{
      wx.showToast({title: '收藏失败',icon:'none'});
      page.setData({isFav: !page.data.isFav});
      return false;
    }});
  },
  //沟通
  contact(){
    if (!app.getUserinfo(true)) {
		return;
	  }
	  let userinfo = app.getUserinfo();
	  if (this.data.job.user_id == userinfo.id) {
		wx.showToast({ title: '不可与自己沟通',icon: 'none'})
		return false;
	  }
	  let chatParams = {
		company_id: this.data.job.publisher_id,
		receive_user_id: this.data.job.user_id,
		content: this.data.job.id,
		to_username: this.data.job.user ? this.data.job.user.nickname : '',
		chat_type: 3, //职位沟通
	  }
	  wx.navigateTo({
		url: '/pages/communicate/index',
		success(res) {
		  res.eventChannel.emit('chatTransfor', chatParams)
		}
	  })
  },
  // 投递简历
  bindApply() {
    if(!app.getUserinfo(true)) {
      return;
    }
    if(this.data.isApplying) {
      return;
    }
    core.post({
      url: 'xilujob.job/apply', data: {job_id:this.data.jobId},
      success: ret => {
		//发送投递成功的消息
		chatIM.sendMessage(this.data.job.user_id, ret.data.id,4);
        wx.showModal({
          title: '提示',
          content: '投递成功',
          showCancel: false
        });
        this.setData({isApplying:true});
      },
      fail: ret => {
        if(ret.code==-1) {
          wx.showModal({
            title: '提示',
            content: '需要先完善简历，现在要去吗？',
            cancelText:'先看看',
            confirmText:'立刻完善',
            success: res=>{
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/my_resume/my_resume'
                });
              }
            }
          });
          return false;
        }
      }
    });
  },
  bindInformJob(event) {
    if(!app.getUserinfo(true)) {
      return;
    }
    wx.navigateTo({url: '/pages/report_detail/report_detail?id='+this.data.jobId});
  },
  bindViewImages(event) {
    let index = event.currentTarget.dataset.index;
    wx.previewImage({
      urls: this.data.images,
      current: this.data.images[index]
    })
  },
  eventOnUserLogin(userinfo) {
    this.getJobDetail();
  },
  onShareAppMessage() {
    let title = '西陆招聘 - ' + this.data.job.job_name;
    let id = this.data.jobId;
    return {
      title: title,
      path: '/pages/jobs_detail/jobs_detail?id='+id,
    };
  },
  bindShowImages() {
    wx.navigateTo({url: '/pages/business_image/business_image',success:(res)=>{
      res.eventChannel.emit('dataTransfer',{images:this.data.images});
    }});
  },
  bindGoCompany() {
    if(this.data.job.publisher_type==2) {
      wx.navigateTo({url: '/pages/recruitment_homepage/recruitment_homepage?id='+this.data.job.publisher_id});
    }else {
      wx.navigateTo({url: '/pages/recruitment_status/recruitment_status?id='+this.data.job.publisher_id});
    }
  },
  bindShowLocation() {
    wx.openLocation({
      latitude: this.data.job.locations[0].lat,
      longitude: this.data.job.locations[0].lng,
      name: this.data.job.locations[0].address,
      address: this.data.job.locations[0].address,
    });
  },
  share() {
    core.get({url:'xilujob.job/poster_info/job_id/'+this.data.job.id, success:ret=>{
      core.setCache('temp', ret.data,10);
      wx.navigateTo({
        url: '/pages/share_post_new/share_post_new'
      })
    }});
  },
  shareTip() {
    this.setData({showShareTip: !this.data.showShareTip});
  }

});
